package easy;

/**
 * Created by daodao on 2017/12/1.
 * Problem 28
 * Description: Implement strStr().
 * Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
 *
 * Example 1: Input: haystack = "hello", needle = "ll"
 *            Output: 2
 * Example 2: Input: haystack = "aaaaa", needle = "bba"
 *            Output: -1
 */
public class ImplementStrStr {
    public static int strStr(String haystack, String needle) {
        int index = -1;
        if (haystack.length() < needle.length()) {
            return index;
        } else if (haystack.length() == needle.length()) {
            return haystack.equals(needle) ? 0 : -1;
        }
        int needleLen = needle.length();
        for (int i = 0; i <= haystack.length() - needleLen; i++) {
            if (haystack.substring(i, i + needleLen).equals(needle)) {
                return i;
            }
        }
        return index;
    }
}
